<?php
namespace Versal\SecurityBundle\Service;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Versal\SecurityBundle\Entity\Usuario;
use Versal\SecurityBundle\Entity\Password;
use Versal\SecurityBundle\Entity\Perfil;
use Versal\SecurityBundle\Entity\User;
use Versal\SecurityBundle\Entity\RoleUser;
use Doctrine\ORM\NoResultException;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of User
 *
 * @author Jorge
 */
class ProveedorUser implements UserProviderInterface
{
    protected $loginDao;
    
    function __construct($userDao) {
        $this->loginDao = $userDao;
    }

    public function getUserDao() {
        return $this->loginDao;
    }

    public function setUserDao($userDao) {
        $this->loginDao = $userDao;
    }
    
    /*
     * Consulta username contra la bd y retorna un objeto User de la interfaz UserInterface
     * 
     */
    public function loadUserByUsername($username)
    {              
        try {
            // The Query::getSingleResult() method throws an exception
            // if there is no record matching the criteria.         
            $usuario = $this->loginDao->getUsuario($username);
            
            if(!$usuario) {
                throw new NoResultException();
            }
            
            $password = $this->loginDao->getPassword($usuario);
          
            if(!$password){
                 throw new NoResultException();
            }
            
            $perfiles = $this->loginDao->getPerfilesUsuario($usuario);
         	
            if(!$perfiles){
                throw new NoResultException();
            }
            
            $user = new User($usuario, $password, $perfiles);
            
           
            /*echo $user->getPassword();
            echo $perfiles[0]->getIdApp();
            echo $perfiles[0]->getRole();*/
           
          
        } catch (NoResultException $e) {
            $message = sprintf(
                'Unable to find an active admin AcmeUserBundle:User object identified by "%s".',
                $username
            );
            throw new UsernameNotFoundException($message, 0, $e);
        }

        return $user;
    }
    
    public function refreshUser(UserInterface $user)
    {
        if (!$user instanceof UserInterface) {
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
        }
        return $this->loadUserByUsername($user->getUsername());    
        //return $user;
    }

    public function supportsClass($class)
    {
       return $class === 'Versal\SecurityBundle\Entity\User';
    }
}

